#include <iostream>
#include "Sock.hpp"

void Usage(std::string proc)
{
    std::cout << "\nUsage: " << proc << " port\n" << std::endl;
}

int main(int argc, char* argv[])
{
    if (argc != 3)
    {
        Usage(argv[1]);
        exit(1);
    }

    int sock = -1;
    std::string server_ip = argv[1];
    uint16_t server_port = atoi(argv[2]);
    bool flag = false; // -> 用来标记连接是否完成

    while (true)
    {
        if (!flag)
        {
            // 1.创建套接字
            sock = Sock::Socket();
            // Sock::SetNonBloack(sock);  // 设置非阻塞

            // 2.连接
            if (!Sock::Connect(sock, server_port, server_ip))
            {
                logMessage(FATAL, "connect error %d: %s", errno, strerror(errno));
                exit(3);
            }
            logMessage(NORMAL, "connect success!");
            flag = true;
        }

        std::cout << "请输入: ";
        std::string message;
        std::getline(std::cin, message);
        if (message == "quit")
        {
            close(sock);
            break;
        }

        ssize_t s = send(sock, message.c_str(), message.size(), 0);
        if (s > 0)
        {
            char buffer[1024];
            ssize_t s = recv(sock, buffer, sizeof(buffer) - 1, 0);
            if (s > 0)
            {
                buffer[s] = 0;
                std::cout << "server回显: " << buffer << std::endl;
            }
            else if (s == 0)
            {
                flag = false; // 对方关闭
                close(sock);
            }
            else
            {
                flag = false;  // 读取失败
                close(sock);
            }
        }
        else
        {
            flag = false; // 发送失败
            close(sock);
        }
    }

    return 0;
}
